package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.AdminStorageService;
import com.cskaoyan.market.service.impl.AdminStorageServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.*;

@MultipartConfig
@WebServlet("/admin/storage/*")
public class AdminStorageController extends HttpServlet {

    AdminStorageService  adminStorageService  = new AdminStorageServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/storage/", "");

        if ("list".equals(op)) {
            list(req, resp);
        }


    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String id = req.getParameter("id");
        String key = req.getParameter("key");
        String type = req.getParameter("type");
        String size = req.getParameter("size");
        String addTime = req.getParameter("add time");
        String updateTime = req.getParameter("updateTime");
        String name = req.getParameter("name");
        String url = req.getParameter("url");
        String deleted = req.getParameter("deleted");


        List<MarketStorage> marketStorages = adminStorageService.list(id, key, type, size, addTime, updateTime, name, url, deleted, page, limit);

        Object o = ResponseUtil.okList(marketStorages);
        String s = JacksonUtil.getObjectMapper().writeValueAsString(o);
        resp.getWriter().write(s);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*
         * 1.获取请求参数
         * 2.调用service层方法
         * 3.返回响应
         * */
        String op = req.getRequestURI().replace(req.getContextPath() + "/admin/storage/", "");

        if (op.equals("create")) {
            create(req, resp);
        }
        if ("delete".equals(op)) {
            delete(req, resp);
        }


    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String op = req.getReader().readLine();
        MarketStorage marketStorage = objectMapper.readValue(op, MarketStorage.class);

        int i = adminStorageService.delete(marketStorage);

        if (i == 1) {
            Object ok = ResponseUtil.ok();
            String s = JacksonUtil.getObjectMapper().writeValueAsString(ok);
            resp.getWriter().write(s);
            return;
        }

        Object fail = ResponseUtil.fail(761, "删除失败");
        String s = JacksonUtil.getObjectMapper().writeValueAsString(fail);
        resp.getWriter().write(s);

    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        Part image = req.getPart("file");


        String submittedFileName = image.getSubmittedFileName();

        String key = UUID.randomUUID() + "-" + submittedFileName;
        MarketStorage marketStorage = new MarketStorage();

        marketStorage.setName(submittedFileName);
        marketStorage.setDeleted(false);
        marketStorage.setKey(key);
        marketStorage.setType(image.getContentType());
        marketStorage.setSize((int) image.getSize());
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        String networkPath = (String) ((Map) req.getServletContext().getAttribute("path")).get("networkPath");
        marketStorage.setUrl(networkPath+"/wx/storage/fetch/" + key);
        String filePath = (String) ((Map) req.getServletContext().getAttribute("path")).get("filePath");


        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        image.write(filePath + "/" + key);

        int effectRows = adminStorageService.create(marketStorage);
        String respJson = null;
        if (effectRows == 1) {
            respJson = objectMapper.writeValueAsString(ResponseUtil.ok(marketStorage));
        } else {
            respJson = objectMapper.writeValueAsString(ResponseUtil.fail(701, "添加失败"));
        }
        resp.getWriter().println(respJson);

    }
}
